/**
 * 带动画的柱状图组件（支持大数据渲染优化）
 */
import React, { useMemo } from 'react';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts';

interface BarData {
  name: string;
  [key: string]: string | number;
}

interface AnimatedBarChartProps {
  data: BarData[];
  bars: Array<{
    dataKey: string;
    name: string;
    color: string;
  }>;
  height?: number;
  showGrid?: boolean;
  showAnimation?: boolean;
}

const AnimatedBarChart: React.FC<AnimatedBarChartProps> = ({
  data,
  bars,
  height = 300,
  showGrid = true,
  showAnimation = true,
}) => {
  // 大数据优化：如果数据超过500条，进行分组聚合
  const optimizedData = useMemo(() => {
    if (data.length <= 500) return data;
    
    // 分组策略：每10条数据合并为1条
    const groupSize = 10;
    const grouped: BarData[] = [];
    
    for (let i = 0; i < data.length; i += groupSize) {
      const group = data.slice(i, i + groupSize);
      const aggregated: BarData = { name: `${group[0].name}~${group[group.length - 1].name}` };
      
      bars.forEach((bar) => {
        aggregated[bar.dataKey] = group.reduce((sum, item) => {
          return sum + (Number(item[bar.dataKey]) || 0);
        }, 0);
      });
      
      grouped.push(aggregated);
    }
    
    return grouped;
  }, [data, bars]);

  // 检测是否需要双Y轴（当有销售额和订单数时，数值差距大，需要双Y轴）
  const needsDualYAxis = useMemo(() => {
    if (bars.length < 2) return false;
    if (optimizedData.length === 0) return false;
    
    // 检查是否有sales和orders字段，且数值差距大
    const hasSales = bars.some(bar => bar.dataKey === 'sales');
    const hasOrders = bars.some(bar => bar.dataKey === 'orders');
    
    if (hasSales && hasOrders) {
      // 计算销售额和订单数的最大值
      const maxSales = Math.max(...optimizedData.map(d => Number(d.sales) || 0));
      const maxOrders = Math.max(...optimizedData.map(d => Number(d.orders) || 0));
      
      // 如果最大值差距超过10倍，使用双Y轴
      return maxSales > 0 && maxOrders > 0 && (maxSales / maxOrders > 10 || maxOrders / maxSales > 10);
    }
    
    return false;
  }, [bars, optimizedData]);

  return (
    <ResponsiveContainer width="100%" height={height}>
      <BarChart
        data={optimizedData}
        margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
      >
        {showGrid && <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />}
        <XAxis
          dataKey="name"
          angle={-45}
          textAnchor="end"
          height={80}
          stroke="#6b7280"
          style={{ fontSize: '12px' }}
        />
        {/* 左Y轴：用于销售额 */}
        <YAxis 
          yAxisId="left"
          stroke="#6b7280" 
          style={{ fontSize: '12px' }}
          label={needsDualYAxis ? { value: '销售额(元)', angle: -90, position: 'insideLeft' } : undefined}
        />
        {/* 右Y轴：用于订单数（当需要双Y轴时） */}
        {needsDualYAxis && (
          <YAxis 
            yAxisId="right"
            orientation="right"
            stroke="#10b981" 
            style={{ fontSize: '12px' }}
            label={{ value: '订单数(单)', angle: 90, position: 'insideRight' }}
          />
        )}
        <Tooltip
          contentStyle={{
            backgroundColor: 'rgba(255, 255, 255, 0.95)',
            border: '1px solid #e5e7eb',
            borderRadius: '8px',
            padding: '8px 12px',
          }}
        />
        <Legend />
        {bars.map((bar, index) => {
          // 如果是订单数且需要双Y轴，使用右Y轴
          const yAxisId = (needsDualYAxis && bar.dataKey === 'orders') ? 'right' : 'left';
          return (
            <Bar
              key={bar.dataKey}
              yAxisId={yAxisId}
              dataKey={bar.dataKey}
              name={bar.name}
              fill={bar.color}
              isAnimationActive={showAnimation}
              animationDuration={600 + index * 100}
              animationEasing="ease-out"
              radius={[8, 8, 0, 0]}
            />
          );
        })}
      </BarChart>
    </ResponsiveContainer>
  );
};

export default AnimatedBarChart;
